package com.example.statistics.common

import android.os.Bundle
import android.view.View
import com.example.statistics.R
import com.example.statistics.bean.DefineInputBean
import com.example.statistics.ex.*
import com.example.statistics.net.DataResult
import com.example.statistics.net.callback.DataDialogHttpCallback
import com.example.statistics.utils.Constants
import com.example.statistics.utils.activityFinish
import com.example.statistics.utils.activityForResult
import com.example.statistics.weight.TextProcessingView
import com.jhj.httplibrary.HttpCall
import com.jhj.httplibrary.model.HttpParams
import com.jhj.slimadapter.SlimAdapter
import kotlinx.android.synthetic.main.activity_recyclerview_refresh.*
import kotlinx.android.synthetic.main.layout_search_bar.*
import org.jetbrains.anko.toast
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.util.*
import kotlin.collections.set

abstract class BaseInputActivity<T> : BaseActivity() {


    /**
     * 扩展参数
     */
    var adapter: SlimAdapter? = null
    private val textProcessingViewList = mutableMapOf<String, TextProcessingView>()
    private val dataMap = mutableMapOf<String, String>()
    open val extentParams = mutableSetOf<Pair<String, Any>>()
    open val isDefault = true
    open val isUpload = true
    abstract val url: String
    abstract val inputDataList: List<DefineInputBean>


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_recyclerview_refresh)
        layout_search_bar.visibility = View.GONE
        topBarRightText("保存") {
            if (!isUpload) {
                return@topBarRightText
            }

            inputDataList.forEach {
                if (!it.isNull && dataMap[it.labelKey].isNullOrEmpty()) {
                    toast(it.labelText.replace("：", "") + "不能为空")
                    return@topBarRightText
                }
            }

            val httpParams = HttpParams()
            dataMap.forEach {
                if (!it.key.startsWith("_")) {
                    httpParams.put(it.key, it.value)
                }

            }
            extentParams.forEach {
                if (!it.first.startsWith("_")) {
                    httpParams.put(it.first, it.second)
                }
            }
            HttpCall.post(url).addParams(httpParams).enqueue(object : DataDialogHttpCallback<T>(this, "保存中...") {

                override val clazzType: Type
                    get() = type(DataResult::class.java, genericType())

                override fun onSuccess(data: T?, resultType: ResultType) {
                    activityFinish("data" to data)
                }
            })
        }
        if (isDefault) {
            initView()
            refresh()
        }
    }

    fun initView() {
        /* SlimAdapter.creator()
             .register<MultiItemTypeModel>(1, R.layout.list_item_define_input) { injector, bean, position ->

             }
             .register<MultiItemTypeModel>(2, R.layout.list_item_define_input) { injector, bean, position ->

             }*/

        adapter = slimAdapter<DefineInputBean>(R.layout.list_item_define_input) { bean ->
            with<TextProcessingView>(R.id.tv_text_view) { textView ->
                textView.afterTextChangedListener { editable, _ ->
                    bean.afterTextChangeListener?.invoke(textView, editable, textProcessingViewList)
                    dataMap[bean.labelKey] = editable.toString()
                }
                textView.labelText = bean.labelText
                textView.unitText = bean.unitText
                textView.style = bean.style
                textView.contentText =
                    (if (bean.labelValue.isNumber() && bean.labelValue?.toFloat() == 0f) "" else bean.labelValue)
                dataMap[bean.labelKey] = bean.labelValue.orEmpty()
                textView.decimalDigits = bean.defaultDecimalPoint
                if ((bean.style == TextProcessingView.STYLE_SELECTOR_JUMPS) && bean.jumps?.first != null) {
                    textView.onContentClicked {
                        activityForResult(bean.jumps.first.invoke()) {
                            try {
                                val data = it?.getSerializableExtra(Constants.DATA)
                                bean.jumps.second.invoke(textView, data, textProcessingViewList)
                            } catch (e: java.lang.Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                } else if ((bean.style == TextProcessingView.STYLE_SELECTOR_JUMPS) && bean.jumps?.first != null) {
                    textView.onContentClicked {
                        activityForResult(bean.jumps.first.invoke()) {
                            try {
                                val data = it?.getSerializableExtra(Constants.DATA)
                                bean.jumps.second.invoke(textView, data, textProcessingViewList)
                            } catch (e: java.lang.Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                } else if (bean.style == TextProcessingView.STYLE_SEARCH && bean.jumps?.first != null) {
                    textView.onSymbolClicked {
                        activityForResult(bean.jumps.first.invoke()) {
                            try {
                                val data = it?.getSerializableExtra(Constants.DATA)
                                bean.jumps.second.invoke(textView, data, textProcessingViewList)
                            } catch (e: java.lang.Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                } else if (bean.style == TextProcessingView.STYLE_SELECTOR) {
                    textView.onContentClicked {
                        if (bean.singleDialog != null) {
                            singleDialog(*bean.singleDialog.first.toTypedArray()) {
                                textView.contentText = it
                                bean.singleDialog.second.invoke(textView, it, textProcessingViewList)
                            }
                        } else if (bean.singleDialogT != null) {
                            singleDialog(*bean.singleDialogT.first.toTypedArray()) {
                                textView.contentText = it.itemName
                                val indexOf = bean.singleDialogT.first.indexOf(it)
                                bean.singleDialogT.second.invoke(textView, indexOf, textProcessingViewList)
                            }
                        }

                    }
                } else if (bean.style == TextProcessingView.STYLE_REFRESH_INPUT || bean.style == TextProcessingView.STYLE_REFRESH) {
                    textView.onRefreshClicked {
                        bean.symbolAction.invoke(textView, textProcessingViewList)
                    }
                } else if (bean.style == TextProcessingView.STYLE_DATE) {
                    textView.datePattern = when (bean.defaultDateFormat) {
                        "HH:mm" -> 1
                        "yyyy-MM-dd HH:mm" -> 2
                        "yyyy-MM" -> 3
                        else -> 0
                    }
                    if (bean.labelValue.isNullOrEmpty())
                        textView.contentText = Date().format(bean.defaultDateFormat)
                }

                if (!textView.unitText.isNullOrBlank()) {
                    textView.onSymbolClicked {
                        bean.symbolAction.invoke(textView, textProcessingViewList)
                    }
                }
                if (bean.clicked != null) {
                    textView.onContentClicked {
                        bean.clicked.invoke(textView, textProcessingViewList)
                    }
                }

                //确保KEY的唯一性
                if (bean.labelKey.isNotEmpty() && textProcessingViewList.keys.contains(bean.labelKey)) {
                    throw java.lang.IllegalArgumentException("Please Check the labelKey parameter of DefineInputBean to make sure it is unique")
                }
                textProcessingViewList[bean.labelKey] = textView
            }
        }.attachTo(recyclerView)
    }

    fun refresh() {
        textProcessingViewList.clear()
        val list = data(inputDataList)
        inputDataList.forEach {
            it.labelValue = textProcessingViewList[it.labelKey]?.labelText
        }
        adapter?.setDataList(list)
    }

    open fun data(list: List<DefineInputBean>): List<DefineInputBean> {
        return list.toMutableList()
    }


    open fun genericType(): Type {
        //获取当前类带有泛型的父类
        val clazz: Type? = this.javaClass.genericSuperclass
        return if (clazz is ParameterizedType) {
            //获取父类的泛型参数（参数可能有多个，获取第一个）
            clazz.actualTypeArguments[0]
        } else {
            throw IllegalArgumentException()
        }
    }
}